<script lang="ts" setup>
import { ref, onMounted, h, nextTick, computed } from 'vue';
import { Card, Table, Spin, message, Button, Input } from 'ant-design-vue';
import { loadDLTData } from '../../utils/dlt/parseDLTData';
import type { DLTRecord } from '../../utils/dlt/parseDLTData';

// 定义表格数据和加载状态
const dataSource = ref<DLTRecord[]>([]);
const filteredDataSource = ref<DLTRecord[]>([]);
const loading = ref(false);
const error = ref('');
const isReverseOrder = ref(false);
const searchKeyword = ref('');
const blueSearchKeyword = ref('');
const searchCount = ref(0);
const blueBallStats = ref<Record<string, number>>({}); // 蓝球统计数据
console.log('初始blueBallStats:', blueBallStats.value);

// 计算属性获取蓝球统计数据
const blueBallStatsComputed = computed(() => {
  console.log('computed: blueBallStats.value =', blueBallStats.value);
  console.log('computed: Object.keys(blueBallStats.value).length =', Object.keys(blueBallStats.value).length);
  return blueBallStats.value;
});

// 蓝球数字列渲染函数
const renderBlueBall = function ({ text }) {
  return h('span', {
    style: {
      display: 'inline-block',
      width: '24px',
      height: '24px',
      borderRadius: '50%',
      backgroundColor: '#1890ff',
      color: 'white',
      textAlign: 'center',
      lineHeight: '24px'
    }
  }, text);
};

// 频率列渲染函数
const renderFrequency = function ({ text }) {
  return h('span', {}, (text * 100).toFixed(2) + '%');
};

// 搜索函数
const handleSearch = () => {
  // 重置搜索结果
  let results = [...dataSource.value];

  // 处理红球搜索
  if (searchKeyword.value.trim()) {
    const redKeywords = searchKeyword.value.toLowerCase().trim().split(/\s+/);
    results = results.filter(item => {
      const redNumbersStr = item.redNumbers.join('');
      return redKeywords.every(keyword => {
        // 检查是否是数字且长度≤5
        const isShortNumber = /^\d{1,5}$/.test(keyword);

        if (isShortNumber) {
          // 只在红球中搜索，确保精确匹配
          return item.redNumbers.some(num => num.toString() === keyword);
        } else {
          // 保持原有搜索逻辑
          return item.issue.toLowerCase().includes(keyword) ||
            item.date.toLowerCase().includes(keyword) ||
            item.redNumbers.some(num => num.toString().includes(keyword)) ||
            redNumbersStr.includes(keyword);
        }
      });
    });
  }

  // 处理篮球搜索
  if (blueSearchKeyword.value.trim()) {
    const blueKeywords = blueSearchKeyword.value.toLowerCase().trim().split(/\s+/);
    results = results.filter(item => {
      return blueKeywords.every(keyword => {
        // 检查是否是数字
        const isNumber = /^\d+$/.test(keyword);

        if (isNumber) {
          // 确保蓝球号码中存在与关键词完全匹配的数字
          return item.blueNumbers.some(num => num.toString() === keyword);
        } else {
          // 非数字关键词的搜索逻辑
          const blueNumbersStr = item.blueNumbers.join('');
          return item.blueNumbers.some(num => num.toString().includes(keyword)) ||
            blueNumbersStr.includes(keyword);
        }
      });
    });
  }

  filteredDataSource.value = results;
  searchCount.value = results.length;
  // 更新蓝球统计数据
  blueBallStats.value = calculateBlueBallStats(results);
};


// 切换排序顺序
const toggleSortOrder = () => {
  isReverseOrder.value = !isReverseOrder.value;
  // 反转数据顺序
  dataSource.value = [...dataSource.value].reverse();
  // 同步更新过滤后的数据
  if (searchKeyword.value.trim()) {
    handleSearch();
  } else {
    filteredDataSource.value = [...dataSource.value];
  }

  // 更新搜索结果数量
  searchCount.value = filteredDataSource.value.length;

  // 重新计算蓝球统计数据
  const stats = calculateBlueBallStats(filteredDataSource.value);
  console.log(`搜索后蓝球统计结果: ${JSON.stringify(stats)}`);
  blueBallStats.value = stats;
  console.log(`搜索后蓝球统计完成，共 ${Object.keys(blueBallStats.value).length} 个蓝球号码`);
};

// 计算蓝球数字出现次数
const calculateBlueBallStats = (data: any[]) => {
  console.log(`开始统计蓝球数据，共 ${data?.length || 0} 条记录`);
  console.log('数据是否为数组:', Array.isArray(data));
  const stats: Record<string, number> = {};
  let validItems = 0;
  let invalidItems = 0;

  if (!data || !Array.isArray(data)) {
    console.log('数据不是有效数组，无法统计');
    return stats;
  }

  if (data.length === 0) {
    console.log('数据数组为空，无法统计');
    return stats;
  }

  // 打印前5条数据样本
  const sampleSize = Math.min(5, data.length);
  console.log(`数据样本 (前${sampleSize}条):`);
  for (let i = 0; i < sampleSize; i++) {
    console.log(`样本 ${i + 1}:`, data[i]);
  }

  data.forEach((item, index) => {
    if (!item) {
      console.log(`第${index}个数据项为null或undefined`);
      invalidItems++;
      return;
    }

    if (!('blueNumbers' in item)) {
      console.log(`第${index}个数据项没有blueNumbers属性`);
      invalidItems++;
      return;
    }

    if (!Array.isArray(item.blueNumbers)) {
      console.log(`第${index}个数据项的blueNumbers不是数组:`, item.blueNumbers);
      invalidItems++;
      return;
    }

    if (item.blueNumbers.length === 0) {
      console.log(`第${index}个数据项的blueNumbers是空数组`);
      invalidItems++;
      return;
    }

    // 检查blueNumbers中的每个元素是否为有效数字
    const validNumbers = item.blueNumbers.filter(num => typeof num === 'number' && !isNaN(num));
    if (validNumbers.length !== item.blueNumbers.length) {
      console.log(`第${index}个数据项的blueNumbers包含无效数字:`, item.blueNumbers);
      invalidItems++;
      return;
    }

    item.blueNumbers.forEach((num: number) => {
      const numStr = num.toString();
      stats[numStr] = (stats[numStr] || 0) + 1;
    });
    validItems++;
  });

  console.log(`统计中间结果:`, stats);

  // 按数字从小到大排序
  const sortedStats: Record<string, number> = {};
  Object.keys(stats).sort((a, b) => parseInt(a) - parseInt(b)).forEach(key => {
    sortedStats[key] = stats[key];
  });

  if (Object.keys(sortedStats).length === 0) {
    console.log('没有统计到蓝球数据');
  } else {
    console.log('统计到的蓝球数据:', sortedStats);
  }

  console.log(`蓝球数据统计完成: 有效项 ${validItems} 个, 无效项 ${invalidItems} 个, 共 ${Object.keys(sortedStats).length} 个不同蓝球号码`);
  return sortedStats;
};

// 页面加载时获取数据
onMounted(async () => {
  loading.value = true;
  console.log('开始加载大乐透数据...');
  try {
    const data = await loadDLTData() || [];
    console.log(`数据加载完成，共 ${data.length} 条记录`);
    dataSource.value = isReverseOrder.value ? [...data].reverse() : data;
    filteredDataSource.value = [...dataSource.value];
    searchCount.value = dataSource.value.length;
    console.log(`数据源初始化完成，共 ${dataSource.value.length} 条记录`);
    // 计算蓝球统计数据
    console.log('开始计算蓝球统计数据...');
    const stats = calculateBlueBallStats(dataSource.value);
    console.log(`蓝球统计结果: ${JSON.stringify(stats)}`);
    console.log(`统计结果长度: ${Object.keys(stats).length}`);

    // 手动创建新对象触发响应式更新
    const newStats = { ...stats };
    console.log('新创建的统计数据:', newStats);
    console.log('新统计数据长度:', Object.keys(newStats).length);

    // 使用nextTick确保DOM更新后再更新蓝球统计数据
    nextTick(() => {
      blueBallStats.value = newStats;
      console.log(`蓝球统计完成，共 ${Object.keys(blueBallStats.value).length} 个蓝球号码`);
      console.log('更新后的blueBallStats.value:', blueBallStats.value);
    });
    if (data.length === 0) {
      message.warning('未找到大乐透数据');
    }
    loading.value = false;
  } catch (err) {
    error.value = '加载数据失败，请稍后重试';
    loading.value = false;
    message.error(error.value);
    console.error('加载大乐透数据出错:', err);
  }
});

// 定义表格列
const columns = [
  {
    title: '期号',
    dataIndex: 'issue',
    key: 'issue',
    width: 80,
  },
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 100,
  },
  {
    title: '红球号码',
    dataIndex: 'redNumbers',
    key: 'redNumbers',
    width: 150,
    customRender: ({ text }: any) => {
      return h('div', null, text.map((num: any, index: any) => {
        return h('span', {
          key: index,
          style: {
            display: 'inline-block',
            width: '24px',
            height: '24px',
            borderRadius: '50%',
            backgroundColor: '#f5222d',
            color: 'white',
            textAlign: 'center',
            lineHeight: '24px',
            marginRight: '5px',
            fontSize: '12px'
          }
        }, num);
      }));
    },
  },
  {
    title: '蓝球号码',
    dataIndex: 'blueNumbers',
    key: 'blueNumbers',
    width: 100,
    customRender: ({ text }: any) => {
      return h('div', null, text.map((num: any, index: any) => {
        return h('span', {
          key: index,
          style: {
            display: 'inline-block',
            width: '24px',
            height: '24px',
            borderRadius: '50%',
            backgroundColor: '#1890ff',
            color: 'white',
            textAlign: 'center',
            lineHeight: '24px',
            marginRight: '5px',
            fontSize: '12px'
          }
        }, num);
      }));
    },
  },
  {
    title: '销售额(元)',
    dataIndex: 'sales',
    key: 'sales',
    width: 120,
    customRender: ({ text }: any) => {
      if (typeof text === 'number') {
        return text.toLocaleString('zh-CN');
      }
      return text;
    },
  },
  {
    title: '一等奖注数',
    dataIndex: 'firstPrizeCount',
    key: 'firstPrizeCount',
    width: 100,
  },
  {
    title: '一等奖金额(元)',
    dataIndex: 'firstPrizeAmount',
    key: 'firstPrizeAmount',
    width: 120,
    customRender: ({ text }: any) => {
      if (typeof text === 'number') {
        return text.toLocaleString('zh-CN');
      }
      return text;
    },
  },
];
</script>

<template>
  <div class="lottery-analyzer">
    <Card title="大乐透数据分析" style="margin-bottom: 20px;">
      <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
        <Button type="primary" @click="toggleSortOrder">
          {{ isReverseOrder ? '关闭倒序' : '开启倒序' }}
        </Button>
        <span style="margin-left: 0; color: #666;">
          共 {{ searchCount }} 条结果
        </span>
        <div style="display: flex; align-items: center;">
          <!-- <span style="margin-right: 10px;">搜索结果: {{ searchCount }}</span> -->
          <!-- <span style="margin-left: 10px; color: #666;">
              共 {{ searchCount }} 条结果
            </span> -->
          <Input placeholder="请输入期号、日期或红球号码搜索" v-model:value="searchKeyword" style="width: 200px; margin-right: 10px;"
            @press-enter="handleSearch" @input="handleSearch" />
          <Input placeholder="请输入蓝球号码搜索" v-model:value="blueSearchKeyword" style="width: 150px; margin-right: 10px;"
            @press-enter="handleSearch" @input="handleSearch" />
          <Button type="primary" @click="handleSearch">
            搜索
          </Button>

        </div>
      </div>
      <Table v-if="dataSource.length > 0" :columns="columns" :dataSource="filteredDataSource"
        :pagination="{ pageSize: 10 }" bordered rowKey="issue" style="width: 100%" />
      <div v-else-if="!loading" style="text-align: center; padding: 50px 0;">
        <p>暂无大乐透数据</p>
      </div>
    </Card>
    <Card title="蓝球数字统计" style="margin-bottom: 20px;">
      <Table v-if="Object.keys(blueBallStats).length > 0" :columns="[
        {
          title: '蓝球数字',
          dataIndex: 'number',
          key: 'number',
          width: 100,
          customRender: renderBlueBall
        },
        {
          title: '出现次数',
          dataIndex: 'count',
          key: 'count',
          width: 100
        },
      ]" :dataSource="Object.keys(blueBallStats).map(function (key) {
        return {
          number: key,
          count: blueBallStats[key],
          frequency: searchCount.value > 0 ? blueBallStats[key] / searchCount.value : 0,
          key: key
        };
      })" :pagination="{ pageSize: 12 }" :rowStyle="{ height: '10px' }" :key="Date.now()" bordered
        style="width: 100%" />
      <div v-else-if="!loading" style="text-align: center; padding: 50px 0;">
        <p>暂无蓝球统计数据</p>
      </div>
    </Card>
  </div>
</template>

<style scoped>
.lottery-analyzer {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
</style>